/*
  学习目标：数据缓存
  步骤：
     
*/

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { delByIdAction, updateByIdAction, setAllAction } from '../store/action';

export default function Main() {
  const { list, type } = useSelector((state) => state);
  const dispatch = useDispatch();

  useEffect(() => {
    // 1. 监听list变化, 存缓存
    localStorage.setItem('todo-list', JSON.stringify(list));
  }, [list]);

  const showList = list.filter((item) => {
    if (type === 'all') return true;
    if (type === 'active') return !item.isDone;
    return item.isDone;
  });
  const isShow = showList.length ? showList.every((item) => item.isDone) : false;

  return (
    <section className="main">
      <input
        onChange={(e) => {
          dispatch(setAllAction(e.target.checked));
        }}
        checked={isShow}
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
      />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {showList.map((item) => (
          <li key={item.id} className={item.isDone ? 'completed' : ''}>
            <div className="view">
              <input
                className="toggle"
                type="checkbox"
                onChange={() => dispatch(updateByIdAction(item.id))}
                checked={item.isDone}
              />
              <label>{item.task}</label>
              <button onClick={() => dispatch(delByIdAction(item.id))} className="destroy"></button>
            </div>
          </li>
        ))}
      </ul>
    </section>
  );
}
